﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Linq;

namespace WorkRecoder
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        XDocument doc = null;
        DateTime dt = DateTime.Now;
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Begin")
            {
                if (lastTime != null && (DateTime.Now - lastTime) > new TimeSpan(0, 10, 0))
                {
                    var dlg = new AddTimeForm();
                    dlg.LastTime = (DateTime)lastTime;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        doc.Root.Add(dlg.Task.Elements());
                        doc.Save(DateTime.Today.ToShortDateString().Replace('/', '-') + ".xml");
                        this.listView1.Items.Clear();
                        Form1_Load(this, null);
                    }
                    lastTime = DateTime.Now;
                    return;
                }

                dt = DateTime.Now;

                button1.Text = "Finished";

                timer1.Enabled = true;
            }
            else
            {
                if (textBox1.Text == string.Empty)
                {
                    MessageBox.Show("You should write something in common!");
                    return;
                }

                var endtime = DateTime.Now;
                var span = endtime - dt;
                var tmp = dt.ToShortTimeString() + "-" +
                    endtime.ToShortTimeString() + "=" + span.Hours + "h" + span.Minutes + "min";
                var date = new string[] { tmp, comboBox1.Text, textBox1.Text };
                var t = new ListViewItem(date);
                t.Tag = span;
                listView1.Items.Add(t);

                doc.Root.Add(new XElement("Row", new XAttribute("TimeSpan", span.ToString()),
                    new XAttribute("EndTime", endtime.ToString()),
                    new XElement("Time", date[0]),
                    new XElement("Item", date[1]),
                    new XElement("Common", date[2])));
                doc.Save(DateTime.Today.ToShortDateString().Replace('/', '-') + ".xml");

                listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                button1.Text = "Begin";


                if (this.timer1.Enabled == true)
                    this.timer1.Enabled = false;

                Text = "";
                t0 = 0;
                lastTime = DateTime.Now;
            }

            textBox1.Text = "";
        }
        DateTime? lastTime = null;
        [PreEmptive.Attributes.Feature("Load")]
        private void Form1_Load(object sender, EventArgs e)
        {
            Text = "WorkRecorder " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            var ini = new jks.IniFiles("WorkRecoder.ini");
            var tmp = ini.ReadString("WorkRecoder", "Item", " ");
            comboBox1.DataSource = tmp.Split(';');

            var file = DateTime.Today.ToShortDateString().Replace('/', '-') + ".xml";
            if (System.IO.File.Exists(file))
            {
                doc = XDocument.Load(file);
                foreach (var i in doc.Root.Elements())
                {
                    var date = new string[] { i.Element("Time").Value, 
                    i.Element("Item").Value,
                    i.Element("Common").Value};
                    var t = new ListViewItem(date);
                    t.Tag = TimeSpan.Parse(i.Attribute("TimeSpan").Value);
                    listView1.Items.Add(t);
                    lastTime = DateTime.Parse(i.Attribute("EndTime").Value);
                }
            }
            else
            {
                doc = new XDocument(new XElement("WorkRecoder"));
            }

            this.timer1.Enabled = false;
            this.timer1.Interval = 1000;
        }

        int t0 = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Text = GetAllTime(t0++);
        }


        public string GetAllTime(int time)
        {
            string hh, mm, ss;
            //int f = time % 100; // 毫秒   
            int s = time; // 转化为秒
            int m = s / 60;     // 分
            int h = m / 60;     // 时
            m = m - h * 60;
            s = s % 60;     // 秒 

            //秒格式00
            if (s < 10)
            {
                ss = "0" + s.ToString();
            }
            else
            {
                ss = s.ToString();
            }

            //分格式00
            if (m < 10)
            {
                mm = "0" + m.ToString();
            }
            else
            {
                mm = m.ToString();
            }

            //时格式00
            if (h < 10)
            {
                hh = "0" + h.ToString();
            }
            else
            {
                hh = h.ToString();
            }


            return hh + ":" + mm + ":" + ss;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var file = dateTimePicker1.Value.ToShortDateString().Replace('/', '-') + ".xml";
            if (System.IO.File.Exists(file))
            {
                listView1.Items.Clear();
                doc = XDocument.Load(file);
                foreach (var i in doc.Root.Elements())
                {
                    var date = new string[] { i.Element("Time").Value, 
                    i.Element("Item").Value,
                    i.Element("Common").Value};
                    var t = new ListViewItem(date);
                    t.Tag = TimeSpan.Parse(i.Attribute("TimeSpan").Value);
                    listView1.Items.Add(t);
                }
            }
            else
                MessageBox.Show("No File Find!");

        }
        [PreEmptive.Attributes.Feature("Statics")]
        private void button2_Click(object sender, EventArgs e)
        {
            var form = new ChartForm();

            var tmp = new Dictionary<string, TimeSpan>();
            foreach (ListViewItem t in listView1.Items)
            {
                if (tmp.Keys.Contains(t.SubItems[1].Text))
                    tmp[t.SubItems[1].Text] += (TimeSpan)t.Tag;
                else
                    tmp.Add(t.SubItems[1].Text, (TimeSpan)t.Tag);
            }

            form.chart.BeginInit();
            foreach (var t in tmp)
            {
                var pnt = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, t.Value.TotalMinutes);
                pnt.LegendText = t.Key;
                form.chart.Series[0].Points.Add(pnt);
            }
            form.chart.EndInit();

            form.chart1.BeginInit();

            var ini = new jks.IniFiles("WorkRecoder.ini");
            var idents = ini.ReadSectionValues("OtherTime");
            foreach (var t in idents)
            {
                var tt = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, double.Parse(t.Value) * 60);
                tt.LegendText = t.Key;
                form.chart1.Series[0].Points.Add(tt);
            }

            var sum = 24 * 60 - tmp.Values.Sum((t) => { return t.Minutes; }) - idents.Values.Sum((t) => { return double.Parse(t); }) * 60;
            var pntt = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, sum);
            pntt.LegendText = "Others";
            form.chart1.Series[0].Points.Add(pntt);
            foreach (var t in tmp)
            {
                var pnt = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, t.Value.TotalMinutes);
                pnt.LegendText = t.Key;
                form.chart1.Series[0].Points.Add(pnt);
            }
            form.chart1.EndInit();

            form.Show();
        }
    }
}
